//
//  GroupRegViewController.m
//  MapLink
//
//  Created by student on 5/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GroupRegViewController.h"
#import "JSON.h"

@implementation GroupRegViewController
@synthesize displayName, deviceID, buffer, delegate;

-(id) init {
	[super initWithNibName:@"GroupRegViewController" bundle:nil];
	[[self navigationItem] setTitle:@"Join Group"];
	
	return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	return [self init];
}

- (void) viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	lebelHelpText.text = @"Enter group credential and select create - to create a new group or join- to join existing group";
	
	[textGroupName becomeFirstResponder];
}


-(IBAction) joinGroup {
	NSLog(@"joinGroup");
	[self addGroupBy:@"join"];
}
-(IBAction) createGroup {
	NSLog(@"createGroup");
	[self addGroupBy:@"create"];
}
-(IBAction)cancel {
	NSLog(@"cancel");
	[self dismissModalViewControllerAnimated:YES];
}
-(void) addGroupBy:(NSString *)action {
	[textGroupName resignFirstResponder];
	[textGroupPassword resignFirstResponder];
	NSURL *url = [NSURL URLWithString:[NSString 
									   stringWithFormat:@"http://mybuddies.emiu.net/group.php?action=%@&device_id=%@&name=%@&group=%@&password=%@",
									   action, 
									   [deviceID stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
									   [displayName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
									   [textGroupName.text  stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
									   [textGroupPassword.text stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
	if(url == NULL) {
		UIAlertView *alertView = [[UIAlertView alloc] 
								  initWithTitle:@"Error" 
								  message:@"GroupName/password is invalid.\nPlease remove SPACE or any other invalid charactors." 
								  delegate:nil 
								  cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	NSLog(@"url is: %@", url);
	[activityIndicatorView startAnimating];
	NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
	[req setHTTPMethod:@"GET"];
	
	conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
	if (conn) {
		self.buffer = [NSMutableData data]; 
	}
}

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
	[buffer setLength:0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
	[buffer appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
	[buffer release];
	[connection release];
	[activityIndicatorView stopAnimating];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
	NSLog(@"Done with bytes %d", [buffer length]);
	NSMutableString *jsonString = [[NSMutableString alloc] initWithBytes:[buffer mutableBytes]
																  length:[buffer length]
																encoding:NSUTF8StringEncoding];
	NSLog(@"result is %@", jsonString);
	NSDictionary *response = [jsonString JSONValue];
	NSString *result = [response objectForKey:@"result"];
	if([result isEqualToString:@"Y"]){
		//success
		[delegate passValue:[response objectForKey:@"group"] forKey:@"groupName"];
		[self dismissModalViewControllerAnimated:YES];
	}else{
		//fail
		UIAlertView *alertView = [[UIAlertView alloc] 
								  initWithTitle:@"Error" 
								  message:[response objectForKey:@"message"] 
								  delegate:nil 
								  cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	
	[jsonString release];
	[connection release];
	[activityIndicatorView stopAnimating];
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[buffer release];
	[delegate release];
    [super dealloc];
}


@end
